package com.excesys.exsecs.energy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.excesys.exsecs.access.entity.AccessDeviceInfo;
import com.excesys.exsecs.access.entity.AccessProduct;
import com.excesys.exsecs.access.service.AccessDeviceInfoService;
import com.excesys.exsecs.access.service.AccessProductService;
import com.excesys.exsecs.common.core.util.R;
import com.excesys.exsecs.common.excel.vo.ErrorMessage;
import com.excesys.exsecs.energy.constant.RedisConstants;
import com.excesys.exsecs.energy.dto.DeviceOnlineInfoDTO;
import com.excesys.exsecs.energy.entity.PowerHourFlow;
import com.excesys.exsecs.energy.entity.RegDev;
import com.excesys.exsecs.energy.entity.RegModel;
import com.excesys.exsecs.energy.mapper.*;
import com.excesys.exsecs.energy.service.RegDevService;
import com.excesys.exsecs.energy.util.PowerConvert;
import com.excesys.exsecs.energy.vo.RegDevExcelVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 能耗设备注册表
 *
 * @author pig
 * @date 2024-02-20 17:10:34
 */
@Service
@RequiredArgsConstructor
public class RegDevServiceImpl extends ServiceImpl<RegDevMapper, RegDev> implements RegDevService {

    private final RegModelMapper regModelMapper;
    private final StringRedisTemplate redisTemplate;
    private final AccessDeviceInfoService accessDeviceInfoService;
    private final AccessProductService accessProductService;
    private final PowerHourFlowMapper powerHourFlowMapper;   //时
    private final PowerDayFlowMapper powerDayFlowMapper;     //天
    private final PowerMonthFlowMapper powerMonthFlowMapper; //月

    @Override
    public Page<RegDev> queryPage(Page page, RegDev regDev) {
        Page<RegDev> regDevPage = this.baseMapper.queryPage(page, regDev);
        if (ObjectUtils.isNotEmpty(regDevPage.getRecords())) {
            regDevPage.getRecords().forEach(it -> {
                Object proData = redisTemplate.opsForHash().get(RedisConstants.PROPERTIES_LIST_KEY, it.getUnitNo());
                if (com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(proData)) {
                    List<JSONObject> channelArr = JSONObject.parseArray(proData.toString(), JSONObject.class);
                    it.setRealTimeList(channelArr);
                }
            });
        }
        return regDevPage;
    }

    @Override
    public List<RegDev> queryRegDevList(List<String> unitNos) {
        return this.baseMapper.queryRegDevList(unitNos);
    }

    @Override
    public List<AccessDeviceInfo> unRegisterDev(String devModel) {
        List<AccessDeviceInfo> accessList = accessDeviceInfoService.getBaseMapper().selectList(Wrappers.<AccessDeviceInfo>lambdaQuery()
                .eq(AccessDeviceInfo::getProductKey, devModel));
        List<AccessDeviceInfo> infos = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(accessList)) {
            List<RegDev> list = this.baseMapper.selectList(Wrappers.<RegDev>lambdaQuery().eq(RegDev::getDevModel, devModel));
            accessList.stream().forEach(l -> {
                List<RegDev> regDevList = list.stream().filter(y -> y.getUnitNo().equals(l.getUnitNo()))
                        .collect(Collectors.toList());
                if (regDevList.isEmpty()) {
                    infos.add(l);
                }
            });
        }
        return infos;
    }

    @Override
    public boolean saveRegDev(List<RegDev> regDevs) {
        return this.saveBatch(regDevs);
    }


    @Override
    public R batchImport(List<RegDevExcelVO> excelVOList, BindingResult bindingResult) {
        // 校验失败集合
        List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
        // 个性化校验逻辑
        List<RegDev> list = this.list();
        // 校验及执行数据插入操作
        for (RegDevExcelVO excel : excelVOList) {
            Set<String> errorMsg = new HashSet<>();

            if (StringUtils.isBlank(excel.getUnitNo())) {
                errorMsg.add("设备位置编码为空,行号为:" + excel.getLineNum() + "\n");
            } else if (StringUtils.isBlank(excel.getUnitName())) {
                errorMsg.add("表计名称不能为空:" + excel.getLineNum() + "\n");
            } else {
                //注册表中是否存在
                boolean existRole = list.stream().anyMatch(dev -> excel.getUnitNo().equals(dev.getUnitNo()));
                if (existRole) {
                    errorMsg.add("设备已注册，请勿重复注册,设备位置编码为:" + excel.getUnitNo() + "\n");
                }
                //设备是否是注册类型中
                DeviceOnlineInfoDTO dto = baseMapper.queryDeviceOnlineInfo(excel.getUnitNo());
                if (ObjectUtils.isNotEmpty(dto)) {
                    List<RegModel> regModels = regModelMapper.selectList(Wrappers.emptyWrapper());
                    if (CollectionUtils.isNotEmpty(regModels)) {
                        List<String> collect = regModels.stream().map(RegModel::getDevModel).collect(Collectors.toList());
                        if (!collect.contains(dto.getDevType())) {
                            errorMsg.add("该设备的型号不存在与注册类型中！,设备位置编码为:" + excel.getUnitNo() + "\n");
                        } else {
                            RegModel regModel = regModelMapper.selectOne(Wrappers.<RegModel>lambdaQuery().eq(RegModel::getDevModel, dto.getDevType()));
                            excel.setEnergyType(regModel.getEnergyType());
                        }
                    }
                } else {
                    errorMsg.add("该设备不存在！,设备位置编码为:" + excel.getUnitNo() + "\n");
                }
            }
            // 数据合法情况
            if (CollUtil.isNotEmpty(errorMsg)) {
                // 数据不合法情况
                errorMessageList.add(new ErrorMessage(excel.getLineNum(), errorMsg));
            }
        }
        if (CollectionUtils.isNotEmpty(errorMessageList)) {
            return R.failed(errorMessageList);
        } else {
            batchInsertExcel(excelVOList);
        }
        return R.ok("本次导入成功");
    }

    private void batchInsertExcel(List<RegDevExcelVO> excelVOList) {
        List<RegDev> list = new ArrayList<>();
        excelVOList.forEach(item -> {
            RegDev regDev = new RegDev();
            BeanUtil.copyProperties(item, regDev);
            list.add(regDev);
        });
        this.saveBatch(list);
    }

    //能耗总量
    @Override
    public JSONObject powerSum(String date) {
        JSONObject result = new JSONObject();//返回数据结构
        //日期时间字符串转换
        DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //获取数据库最新的时间格式 开始时间 与 结束时间
        Map newestTime = getNewestTime(date, date);
        //当日时间与当月时间
        String startTime = null;//起始时间
        String endTime = null;//结束时间
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        if (!newestTime.isEmpty()) {
            startDateTime = LocalDateTime.parse(newestTime.get("startTime").toString(), isoFormatter);
            startTime = startDateTime.format(customFormatter);
            endDateTime = LocalDateTime.parse(newestTime.get("endTime").toString(), isoFormatter);
            endTime = endDateTime.format(customFormatter);
        }
        //日
        if (date.matches("\\d{4}-\\d{2}-\\d{2}")) {
            //获取当天的时间用来做判断用
            LocalDate today = LocalDate.now();
            if (!date.equals(today.toString())) {
                if (startDateTime != null) {
                    LocalDateTime nextDayDateTime = startDateTime.plusDays(1);
                    // 格式化并打印明天的日期时间
                    LocalDateTime dateTime1 = LocalDateTime.parse(nextDayDateTime.toString(), isoFormatter);
                    endTime = dateTime1.format(customFormatter);
                }
            }
        }
        //月
        if (date.matches("^\\d{4}-(0[1-9]|1[0-2])$")) {
            //获取当前月
            YearMonth month = YearMonth.from(LocalDate.now());
            if (!date.equals(month.toString())) {
                if (startDateTime != null) {
                    LocalDateTime nextMonthDateTime = startDateTime.plusMonths(1);
                    // 格式化并打印明天的日期时间
                    LocalDateTime dateTime1 = LocalDateTime.parse(nextMonthDateTime.toString(), isoFormatter);
                    endTime = dateTime1.format(customFormatter);
                }
            }
        }
        //年
        if (date.matches("^\\d{4}$")) {
            // 获取当前年份
            Year year = Year.now();
            if (!date.equals(year.toString())) {
                String years = String.valueOf(Integer.parseInt(date) + 1);
                Map yearsTime = getNewestTime(years, years);
                if (!yearsTime.isEmpty()) {
                    endTime = LocalDateTime.parse(yearsTime.get("startTime").toString(), isoFormatter).format(customFormatter);
                }
            }
        }
        //电
        double eStartSum = this.powerHourFlowMapper.sumPowerAllNumber("1", startTime);
        double eEndSum = this.powerHourFlowMapper.sumPowerAllNumber("1", endTime);
        double eSumPower = 0;
        if (eStartSum != 0 && eEndSum != 0) {
            eSumPower = (eEndSum - eStartSum) / 10000;//计算万毫安
        }
        result.put("eSumPower", new BigDecimal(eSumPower).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        //水
        double waterStartSum = this.powerHourFlowMapper.sumPowerAllNumber("2", startTime);
        double waterEndSum = this.powerHourFlowMapper.sumPowerAllNumber("2", endTime);
        double waterSumPower = 0;
        if (waterStartSum != 0 && waterEndSum != 0) {
            waterSumPower = waterEndSum - waterStartSum;
        }
        result.put("waterSumPower", new BigDecimal(waterSumPower).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        //气
        double gasStartSum = this.powerHourFlowMapper.sumPowerAllNumber("3", startTime);
        double gasEndSum = this.powerHourFlowMapper.sumPowerAllNumber("3", endTime);
        double gasSumPower = 0;
        if (gasStartSum != 0 && gasEndSum != 0) {
            gasSumPower = gasEndSum - gasStartSum;
        }
        result.put("gasSumPower", new BigDecimal(gasSumPower).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        //冷
        double coldStartSum = this.powerHourFlowMapper.sumPowerAllNumber("4", startTime);
        double coldEndSum = this.powerHourFlowMapper.sumPowerAllNumber("4", endTime);
        double coldSumPower = 0;
        if (coldStartSum != 0 && coldEndSum != 0) {
            coldSumPower = coldEndSum - coldStartSum;
        }
        result.put("coldSumPower", new BigDecimal(coldSumPower).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        return result;
    }


    @Override
    public JSONObject powerUnit(String date, Double area) {
        JSONObject result = new JSONObject();//返回数据结构
        //日期时间字符串转换
        DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //获取数据库最新的时间格式 开始时间 与 结束时间
        Map newestTime = getNewestTime(date, date);
        //当日时间与当月时间
        String startTime = null;//起始时间
        String endTime = null;//结束时间
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        if (!newestTime.isEmpty()) {
            startDateTime = LocalDateTime.parse(newestTime.get("startTime").toString(), isoFormatter);
            startTime = startDateTime.format(customFormatter);
            endDateTime = LocalDateTime.parse(newestTime.get("endTime").toString(), isoFormatter);
            endTime = endDateTime.format(customFormatter);
        }
        //日
        if (date.matches("\\d{4}-\\d{2}-\\d{2}")) {
            //获取当天的时间用来做判断用
            LocalDate today = LocalDate.now();
            if (!date.equals(today.toString())) {
                LocalDateTime nextDayDateTime = startDateTime.plusDays(1);
                // 格式化并打印明天的日期时间
                LocalDateTime dateTime1 = LocalDateTime.parse(nextDayDateTime.toString(), isoFormatter);
                endTime = dateTime1.format(customFormatter);
            }
        }
        //月
        if (date.matches("^\\d{4}-(0[1-9]|1[0-2])$")) {
            //获取当前月
            YearMonth month = YearMonth.from(LocalDate.now());
            if (!date.equals(month.toString())) {
                LocalDateTime nextMonthDateTime = startDateTime.plusMonths(1);
                // 格式化并打印明天的日期时间
                LocalDateTime dateTime1 = LocalDateTime.parse(nextMonthDateTime.toString(), isoFormatter);
                endTime = dateTime1.format(customFormatter);
            }
        }
        //年
        if (date.matches("^\\d{4}$")) {
            // 获取当前年份
            Year year = Year.now();
            if (!date.equals(year.toString())) {
                String years = String.valueOf(Integer.parseInt(date) + 1);
                Map yearsTime = getNewestTime(years, years);
                if (!yearsTime.isEmpty()) {
                    endTime = LocalDateTime.parse(yearsTime.get("startTime").toString(), isoFormatter).format(customFormatter);
                }
            }
        }
        double eStartSum = this.powerHourFlowMapper.sumPowerAllNumber("1", startTime);
        double eEndSum = this.powerHourFlowMapper.sumPowerAllNumber("1", endTime);
        double eSumPower = 0;
        if (eStartSum != 0 && eEndSum != 0) {
            eSumPower = eEndSum - eStartSum;
        }
        //单位面积能耗
        result.put("unitAreaPower", new BigDecimal(eSumPower / area.doubleValue()).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue());
        //人均单位能耗
        result.put("capitaUnitPower", 0);
        return result;
    }

    @Override
    public JSONObject powerTrend(String startDate, String endDate, String energyType, String compareType) throws ParseException {
        JSONObject jsonPower = new JSONObject();
        //日
        if (startDate.matches("\\d{4}-\\d{2}-\\d{2}") && endDate.matches("\\d{4}-\\d{2}-\\d{2}")) {
            LocalDate today = LocalDate.now();
            //当天数据
            if (startDate.equals(today.toString()) && endDate.equals(today.toString())) {
                //日能耗柱状图
                jsonPower = powerDayLayer(startDate, endDate, energyType, compareType);
            } else {
                if (startDate.equals(endDate)) {
                    //其他天的数据
                    jsonPower = powerDayLayer(startDate, endDate, energyType, compareType);
                } else {
                    jsonPower = powerDaySectionLayer(startDate, endDate, energyType, compareType);
                }
            }
        }
        //月
        if (startDate.matches("^\\d{4}-(0[1-9]|1[0-2])$") && endDate.matches("^\\d{4}-(0[1-9]|1[0-2])$")) {
            //1.获取当前月
            YearMonth currentMonth = YearMonth.from(LocalDate.now());
            //前月数据
            if (startDate.equals(currentMonth.toString()) && endDate.equals(currentMonth.toString())) {
                jsonPower = powerMonthLayer(startDate, endDate, energyType, compareType);
            } else {
                if (startDate.equals(endDate)) {
                    jsonPower = powerMonthLayer(startDate, endDate, energyType, compareType);
                } else {
                    jsonPower = powerMonthSectionLayer(startDate, endDate, energyType, compareType);
                }
            }
        }
        // 年
        if (startDate.matches("^\\d{4}$") && endDate.matches("^\\d{4}$")) {
            //1.获取当前年
            Year month = Year.from(LocalDate.now());
            System.out.println();
            if (startDate.equals(month.toString()) && endDate.equals(month.toString())) {
                jsonPower = powerYearsLayer(startDate, endDate, energyType, compareType);
            } else {
                if (startDate.equals(endDate)) {
                    jsonPower = powerYearsLayer(startDate, endDate, energyType, compareType);
                } else {
                    jsonPower = powerYearsSectionLayer(startDate, endDate, energyType, compareType);
                }
            }
        }
        return jsonPower;
    }


    //日能耗柱状图
    public JSONObject powerDayLayer(String startDate, String endDate, String energyType, String compareType) {
        JSONObject jsonPower = new JSONObject();
        /*图表通用数组*/
        JSONObject chartData = new JSONObject();
        List<String> xData = new ArrayList<>();
        List<Double> yData1 = new ArrayList<>();//当前
        List<Double> yData2 = new ArrayList<>();//其他
        //图层时间
        String layerStartTime = null;
        String layerEndTime = null;
        String otherStartTime = null;
        String otherEndTime = null;
        List<Map<String, Object>> otherChartPowerList = new ArrayList<>();
        List<Map<String, Object>> chartPowerList = new ArrayList<>();
        // Create图层时间
        layerStartTime = startDate + " 01";//开始时间
        // 解析给定的日期字符串
        LocalDate givenDate = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        // 获取明天的日期
        LocalDate nextDay = givenDate.plusDays(1);
        layerEndTime = nextDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00";
        if (compareType.equals("2")) {
            // Create图层其他时间
            // 获取昨天的日期
            LocalDate previousDay = givenDate.minusDays(1);
            otherStartTime = previousDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 01";
            otherEndTime = endDate + " 00";
            //其他时间段
            otherChartPowerList = this.powerHourFlowMapper.powerAnalyse(otherStartTime, otherEndTime, energyType);
        }
        /* 图表 */
        //最新数据
        chartPowerList = this.powerHourFlowMapper.powerAnalyse(layerStartTime, layerEndTime, energyType);
        for (int h = 0; h < 24; h++) {
            String strHour = String.format("%02d", h);
            xData.add(strHour);
            List<Map<String, Object>> yearData = chartPowerList.stream().filter(bo -> bo.get("createTime").equals(strHour))
                    .collect(Collectors.toList());
            Double powerData = null;
            Double otherData = null;
            if (!yearData.isEmpty()) {
                if (energyType.equals("")) {
                    powerData = Double.parseDouble(yearData.get(0).get("incrValue").toString());
                    double eSumPowerCoal = 0d;
                    eSumPowerCoal += PowerConvert.electricToCoal(powerData);
                    yData1.add(new BigDecimal(eSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                } else {
                    powerData = Double.parseDouble(yearData.get(0).get("incrValue").toString());
                    yData1.add(new BigDecimal(powerData).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
            } else {
                yData1.add(0.0);
            }
            List<Map<String, Object>> otherYearData = new ArrayList<>();
            if (!otherChartPowerList.isEmpty()) {
                otherYearData = otherChartPowerList.stream().filter(bo -> bo.get("createTime").equals(strHour))
                        .collect(Collectors.toList());
            }
            if (!otherYearData.isEmpty()) {
                if (energyType.equals("")) {
                    otherData = Double.parseDouble(otherYearData.get(0).get("incrValue").toString());
                    double eSumPowerCoal = 0d;
                    eSumPowerCoal += PowerConvert.electricToCoal(otherData);
                    yData2.add(new BigDecimal(eSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                } else {
                    otherData = Double.parseDouble(otherYearData.get(0).get("incrValue").toString());
                    yData2.add(new BigDecimal(otherData).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
            } else {
                yData2.add(0.0);
            }
        }
        chartData.put("xData", xData);
        chartData.put("yData1", yData1);
        chartData.put("yData2", yData2);
        jsonPower.put("chartData", chartData);//图标
        jsonPower.put("tableData", chartPowerList);//表格
        return jsonPower;
    }

    //日 - 区间 - 柱状图
    public JSONObject powerDaySectionLayer(String startDate, String endDate, String energyType, String compareType) throws ParseException {
        JSONObject jsonPower = new JSONObject();
        /*图表通用数组*/
        JSONObject chartData = new JSONObject();
        List<String> xData = new ArrayList<>();
        List<Double> yData1 = new ArrayList<>();//当前
        //图层时间
        String layerStartTime = null;
        String layerEndTime = null;
        //模糊查询的字段
        List<Map<String, Object>> chartPowerList = new ArrayList<>();//最新数据
        List<Map<String, Object>> chartPowerListtable = new ArrayList<>();//区间表格数据接受
        // 使用输入格式解析日期字符串
        SimpleDateFormat inputSdf = new SimpleDateFormat("yyyyMMdd");
        // 使用输出格式格式化日期对象
        SimpleDateFormat outputSdf = new SimpleDateFormat("yyyy-MM-dd");
        layerStartTime = startDate.replaceAll("-", "");
        layerEndTime = endDate.replaceAll("-", "");
        /* 图表 */
        //最新数据
        chartPowerList = this.powerDayFlowMapper.powerDayAnalyse(layerStartTime, layerEndTime, energyType);
        if (!chartPowerList.isEmpty()) {
            for (Map<String, Object> mapList : chartPowerList) {
                if (energyType.equals("")) {
                    xData.add(outputSdf.format(inputSdf.parse(mapList.get("timeValue").toString())));
                    double eSumPowerCoal = 0d;
                    eSumPowerCoal += PowerConvert.electricToCoal(Double.parseDouble(mapList.get("incrValue").toString()));
                    yData1.add(new BigDecimal(eSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                } else {
                    xData.add(outputSdf.format(inputSdf.parse(mapList.get("timeValue").toString())));
                    yData1.add(new BigDecimal(Double.parseDouble(mapList.get("incrValue").toString())).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }

                Map<String, Object> otherChartMap = new HashMap<>();
                double eSumPowerCoal = 0d;
                eSumPowerCoal += PowerConvert.electricToCoal(Double.parseDouble(mapList.get("incrValue").toString()));
                otherChartMap.put("incrValue", new BigDecimal(eSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                otherChartMap.put("createTime", mapList.get("createTime").toString());
                otherChartMap.put("timeValue", outputSdf.format(inputSdf.parse(mapList.get("timeValue").toString())));
                chartPowerListtable.add(otherChartMap);
            }
        }
        chartData.put("xData", xData);
        chartData.put("yData1", yData1);
        jsonPower.put("chartData", chartData);//图标
        jsonPower.put("tableData", chartPowerListtable);//表格
        return jsonPower;
    }

    //月能耗柱状图
    public JSONObject powerMonthLayer(String startDate, String endDate, String energyType, String compareType) throws ParseException {
        JSONObject jsonPower = new JSONObject();
        /*图表通用数组*/
        JSONObject chartData = new JSONObject();
        List<String> xData = new ArrayList<>();
        List<Double> yData1 = new ArrayList<>();//当前
        List<Double> yData2 = new ArrayList<>();//其他
        //图层时间
        List<Map<String, Object>> otherChartPowerList = new ArrayList<>();//其他时间段
        List<Map<String, Object>> chartPowerList = new ArrayList<>();//最新数据
        //模糊查询的字段
        String date = startDate.replaceAll("-", "");
        if (compareType.equals("2")) {
            //开始时间与结束时间是否相同
            // 创建一个YearMonth对象
            YearMonth yearMonth = YearMonth.of(Integer.parseInt(startDate.substring(0, 4)), Integer.parseInt(startDate.substring(6, 7)));
            // 获取上一个月的YearMonth
            YearMonth previousYearMonth = yearMonth.minusMonths(1);
            String BlurDate = previousYearMonth.toString().replaceAll("-", "");
            //环比 柱状图 其他时间段
            otherChartPowerList = this.powerDayFlowMapper.powerAnalyse(BlurDate, energyType);
        }
        /* 图表 */
        //最新数据
        chartPowerList = this.powerDayFlowMapper.powerAnalyse(date, energyType);
        for (int day = 1; day <= 31; day++) {
            // 输出两位数的日期，如果是一位数则在前面补0
            String strDay = String.format("%02d", day);
            xData.add(strDay);
            List<Map<String, Object>> dayData = chartPowerList.stream().filter(bo -> bo.get("createTime").equals(strDay))
                    .collect(Collectors.toList());
            Double powerDayData = null;
            Double otherChart = null;
            if (!dayData.isEmpty()) {
                if (energyType.equals("")) {
                    powerDayData = Double.parseDouble(dayData.get(0).get("incrValue").toString());
                    double eSumPowerCoal = 0d;
                    eSumPowerCoal += PowerConvert.electricToCoal(powerDayData);
                    yData1.add(new BigDecimal(eSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                } else {
                    powerDayData = Double.parseDouble(dayData.get(0).get("incrValue").toString());
                    yData1.add(new BigDecimal(powerDayData).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
            } else {
                yData1.add(0.0);
            }
            List<Map<String, Object>> otherChartData = new ArrayList<>();
            if (!otherChartPowerList.isEmpty()) {
                otherChartData = otherChartPowerList.stream().filter(bo -> bo.get("createTime").equals(strDay))
                        .collect(Collectors.toList());
            }
            if (!otherChartData.isEmpty()) {
                if (energyType.equals("")) {
                    otherChart = Double.parseDouble(otherChartData.get(0).get("incrValue").toString());
                    double eSumPowerCoal = 0d;
                    eSumPowerCoal += PowerConvert.electricToCoal(otherChart);
                    yData2.add(new BigDecimal(eSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                } else {
                    otherChart = Double.parseDouble(otherChartData.get(0).get("incrValue").toString());
                    yData2.add(new BigDecimal(otherChart).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
            } else {
                yData2.add(0.0);
            }
        }
        chartData.put("xData", xData);
        chartData.put("yData1", yData1);
        chartData.put("yData2", yData2);
        jsonPower.put("chartData", chartData);//图标
        jsonPower.put("tableData", chartPowerList);//表格
        return jsonPower;
    }

    //月 - 区间 - 柱状图
    public JSONObject powerMonthSectionLayer(String startDate, String endDate, String energyType, String compareType) throws ParseException {
        JSONObject jsonPower = new JSONObject();
        /*图表通用数组*/
        JSONObject chartData = new JSONObject();
        List<String> xData = new ArrayList<>();
        List<Double> yData1 = new ArrayList<>();//当前
        //图层时间
        String layerStartTime = null;
        String layerEndTime = null;
        List<Map<String, Object>> chartPowerList = new ArrayList<>();//最新数据
        List<Map<String, Object>> chartPowerListtable = new ArrayList<>();//区间表格数据接受

        // 使用输入格式解析日期字符串
        SimpleDateFormat inputSdf = new SimpleDateFormat("yyyyMM");
        // 使用输出格式格式化日期对象
        SimpleDateFormat outputSdf = new SimpleDateFormat("yyyy-MM");
        layerStartTime = startDate.replaceAll("-", "");
        layerEndTime = endDate.replaceAll("-", "");
        /* 图表 */
        //最新数据
        chartPowerList = this.powerMonthFlowMapper.powerMonthAnalyse(layerStartTime, layerEndTime, energyType);
        for (Map<String, Object> mapList : chartPowerList) {
            xData.add(outputSdf.format(inputSdf.parse(mapList.get("timeValue").toString())));
            if (energyType.equals("")) {
                double eSumPowerCoal = 0d;
                eSumPowerCoal += PowerConvert.electricToCoal(Double.parseDouble(mapList.get("incrValue").toString()));
                yData1.add(new BigDecimal(eSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            } else {
                yData1.add(new BigDecimal(Double.parseDouble(mapList.get("incrValue").toString())).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            }
            Map<String, Object> otherChartMap = new HashMap<>();
            double eSumPowerCoal = 0d;
            eSumPowerCoal += PowerConvert.electricToCoal(Double.parseDouble(mapList.get("incrValue").toString()));
            otherChartMap.put("incrValue", new BigDecimal(eSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            otherChartMap.put("createTime", mapList.get("createTime").toString());
            otherChartMap.put("timeValue", outputSdf.format(inputSdf.parse(mapList.get("timeValue").toString())));
            chartPowerListtable.add(otherChartMap);
        }
        chartData.put("xData", xData);
        chartData.put("yData1", yData1);
        jsonPower.put("chartData", chartData);//图标
        jsonPower.put("tableData", chartPowerListtable);//表格
        return jsonPower;
    }

    //年能耗柱状图
    public JSONObject powerYearsLayer(String startDate, String endDate, String energyType, String compareType) throws ParseException {
        JSONObject jsonPower = new JSONObject();
        /*图表通用数组*/
        JSONObject chartData = new JSONObject();
        List<String> xData = new ArrayList<>();
        List<Double> yData1 = new ArrayList<>();//当前
        List<Double> yData2 = new ArrayList<>();//其他
        //图层时间
        String layerStartTime = null;
        String otherStartTime = null;
        List<Map<String, Object>> otherChartPowerList = new ArrayList<>();
        List<Map<String, Object>> chartPowerList = new ArrayList<>();
        layerStartTime = startDate;
        //上年
        if (compareType.equals("1")) {
            otherStartTime = String.valueOf(Integer.parseInt(startDate) - 1);
            otherChartPowerList = this.powerMonthFlowMapper.powerAnalyse(otherStartTime, energyType);
        }
        /*图表*/
        //最新数据
        chartPowerList = this.powerMonthFlowMapper.powerAnalyse(layerStartTime, energyType);
        for (int m = 1; m < 13; m++) {
            String strMonth = String.format("%02d", m);
            List<Map<String, Object>> chartYearData = chartPowerList.stream().filter(bo -> bo.get("createTime").equals(strMonth))
                    .collect(Collectors.toList());
            Double YearData = null;
            Double chartYear = null;
            if (!chartYearData.isEmpty()) {
                if (energyType.equals("")) {
                    YearData = Double.parseDouble(chartYearData.get(0).get("incrValue").toString());
                    double eSumPowerCoal = 0d;
                    eSumPowerCoal += PowerConvert.electricToCoal(YearData);
                    yData1.add(new BigDecimal(eSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                } else {
                    YearData = Double.parseDouble(chartYearData.get(0).get("incrValue").toString());
                    yData1.add(new BigDecimal(YearData).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
            } else {
                yData1.add(0.0);
            }
            List<Map<String, Object>> otherChartYearData = new ArrayList<>();
            if (!otherChartPowerList.isEmpty()) {
                otherChartYearData = otherChartPowerList.stream().filter(bo -> bo.get("createTime").equals(strMonth))
                        .collect(Collectors.toList());
            }
            if (!otherChartYearData.isEmpty()) {
                if (energyType.equals("")) {
                    chartYear = Double.parseDouble(otherChartYearData.get(0).get("incrValue").toString());
                    double eSumPowerCoal = 0d;
                    eSumPowerCoal += PowerConvert.electricToCoal(chartYear);
                    yData2.add(new BigDecimal(eSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                } else {
                    chartYear = Double.parseDouble(otherChartYearData.get(0).get("incrValue").toString());
                    yData2.add(chartYear);
                }
            } else {
                yData2.add(0.0);
            }
            xData.add(strMonth);
        }
        chartData.put("xData", xData);
        chartData.put("yData1", yData1);
        chartData.put("yData2", yData2);
        jsonPower.put("chartData", chartData);//图标
        jsonPower.put("tableData", chartPowerList);//表格
        return jsonPower;
    }

    //年 - 区间 - 柱状图
    public JSONObject powerYearsSectionLayer(String startDate, String endDate, String energyType, String compareType) {
        JSONObject jsonPower = new JSONObject();
        /*图表通用数组*/
        JSONObject chartData = new JSONObject();
        List<String> xData = new ArrayList<>();
        List<Double> yData1 = new ArrayList<>();//当前
        //图层时间
        String layerStartTime = null;
        String layerEndTime = null;
        List<Map<String, Object>> chartPowerList = new ArrayList<>();
        List<Map<String, Object>> chartPowerListtable = new ArrayList<>();//区间表格数据接受
        if (compareType.equals("0")) {
            //年的区间 开始时间
            Calendar calendar = Calendar.getInstance();
            calendar.set(Integer.parseInt(startDate), Calendar.JANUARY, 1); // 年份、月份（从0开始，1代表1月）、日期
            layerStartTime = new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(calendar.getTime());
            //年的区间 接受时间
            calendar.set(Integer.parseInt(endDate), Calendar.DECEMBER, 31); // 年份、月份（从0开始，1代表1月）、日期
            layerEndTime = new SimpleDateFormat("yyyy-MM-dd 23:00:00").format(calendar.getTime());
            /*图表*/
            //最新数据
            chartPowerList = this.powerHourFlowMapper.powerHourAnalyse(layerStartTime, layerEndTime, energyType);
            for (Map<String, Object> mapList : chartPowerList) {
                xData.add(mapList.get("timeYear").toString());
                double eSumPowerCoal = 0d;
                eSumPowerCoal += PowerConvert.electricToCoal(Double.parseDouble(mapList.get("incrValue").toString()));
                yData1.add(new BigDecimal(eSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                Map<String, Object> otherChartMap = new HashMap<>();
                otherChartMap.put("incrValue", eSumPowerCoal);
                otherChartMap.put("createTime", mapList.get("timeYear").toString());
                otherChartMap.put("timeValue", mapList.get("timeYear").toString());
                chartPowerListtable.add(otherChartMap);
            }
        }
        chartData.put("xData", xData);
        chartData.put("yData1", yData1);
        jsonPower.put("chartData", chartData);//图标
        jsonPower.put("tableData", chartPowerListtable);//表格
        return jsonPower;
    }

    //能耗概览
    @Override
    public JSONObject powerOverview(String startDate, String endDate, String compareType) {
        JSONObject result = new JSONObject();//返回数据结构
        //日期时间字符串转换
        DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //获取数据库最新的时间格式 开始时间 与 结束时间
        Map newestTime = getNewestTime(startDate, endDate);
        //当日时间与当月时间
        String startTime = null;//起始时间
        String endTime = null;//结束时间
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        if (!newestTime.isEmpty()) {
            startDateTime = LocalDateTime.parse(newestTime.get("startTime").toString(), isoFormatter);
            startTime = startDateTime.format(customFormatter);
            endDateTime = LocalDateTime.parse(newestTime.get("endTime").toString(), isoFormatter);
            endTime = endDateTime.format(customFormatter);
        }
        //环比时间
        String YoYStartTime = null;
        String YoYendTime = null;

        //日
        if (startDate.matches("\\d{4}-\\d{2}-\\d{2}") && endDate.matches("\\d{4}-\\d{2}-\\d{2}")) {
            //获取左天的时间用来做判断用
            LocalDate today = LocalDate.now();
            // 判断开始时间和结束时间是否都在今天
            if (!startDate.equals(today.toString()) && !endDate.equals(today.toString())) {
                if (startDate.equals(endDate)) {
                    LocalDate days = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusDays(1);
                    //获取开始时间与结束时间 用来做判断用 明天有没有数据, 没有数据则不进入
                    Map newest = getNewestTime(days.toString(), days.toString());
                    if (!newest.isEmpty()) {
                        LocalDateTime nextDayDateTime = startDateTime.plusDays(1);
                        // 格式化并打印明天的日期时间
                        LocalDateTime dateTime1 = LocalDateTime.parse(nextDayDateTime.toString(), isoFormatter);
                        endTime = dateTime1.format(customFormatter);
                    }
                    //2 代表 环比逻辑处理 - 上期能耗
                    if (compareType.equals("2")) {
                        YoYStartTime = LocalDateTime.parse(startDateTime.minusDays(1).toString(), isoFormatter).format(customFormatter);
                        YoYendTime = startTime;
                    }
                } else {
                    //区间查询，根据结束时间，获取明天的00:00:00点
                    endTime = LocalDateTime.parse(endTime, customFormatter).toLocalDate().plusDays(1).atStartOfDay().format(customFormatter);
                }
            } else {
                //2 代表 环比逻辑处理 - 上期能耗
                if (compareType.equals("2")) {
                    YoYStartTime = LocalDateTime.parse(startDateTime.minusDays(1).toString(), isoFormatter).format(customFormatter);
                    YoYendTime = LocalDateTime.parse(endDateTime.minusDays(1).toString(), isoFormatter).format(customFormatter);
                }
            }
        }
        //月
        if (startDate.matches("^\\d{4}-(0[1-9]|1[0-2])$") && endDate.matches("^\\d{4}-(0[1-9]|1[0-2])$")) {
            //1.获取当前月
            YearMonth currentMonth = YearMonth.from(LocalDate.now());
            if (!startDate.equals(currentMonth.toString()) && !endDate.equals(currentMonth.toString())) {
                if (startDate.equals(endDate)) {
                    YearMonth month = YearMonth.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM")).plusMonths(1);
                    //获取开始时间与结束时间 用来做判断用 明天有没有数据, 没有数据则不进入
                    Map newest = getNewestTime(month.toString(), month.toString());
                    if (!newest.isEmpty()) {
                        // 格式化并打印明天的日期时间
                        endTime = LocalDateTime.parse(newest.get("startTime").toString(), isoFormatter).format(customFormatter);
                    }
                    //2 代表 环比逻辑处理 - 上期能耗
                    if (compareType.equals("2")) {
                        YoYStartTime = LocalDateTime.parse(startDateTime.minusMonths(1).toString(), isoFormatter).format(customFormatter);
                        YoYendTime = startTime;
                    }
                } else {
                    //区间查询，根据结束时间，获取明天的00:00:00点
                    YearMonth month = YearMonth.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM")).plusMonths(1);
                    //获取开始时间与结束时间 用来做判断用 明天有没有数据, 没有数据则不进入
                    Map newest = getNewestTime(month.toString(), month.toString());
                    if (!newest.isEmpty()) {
                        // 格式化并打印明天的日期时间
                        endTime = LocalDateTime.parse(newest.get("startTime").toString(), isoFormatter).format(customFormatter);
                    }
                }
            } else {
                //2 代表 环比逻辑处理 - 上期能耗
                if (compareType.equals("2")) {
                    YoYStartTime = LocalDateTime.parse(startDateTime.minusMonths(1).toString(), isoFormatter).format(customFormatter);
                    YoYendTime = LocalDateTime.parse(endDateTime.minusMonths(1).toString(), isoFormatter).format(customFormatter);
                }
            }
        }
        //年
        if (startDate.matches("^\\d{4}$") && endDate.matches("^\\d{4}$")) {
            //1.获取当前年
            Year month = Year.from(LocalDate.now());
            if (!startDate.equals(month.toString()) && !endDate.equals(month.toString())) {
                if (startDate.equals(endDate)) {
                    Year year = Year.parse(startDate, DateTimeFormatter.ofPattern("yyyy")).plusYears(1);
                    //获取开始时间与结束时间 用来做判断用 明天有没有数据, 没有数据则不进入
                    Map newest = getNewestTime(year.toString(), year.toString());
                    if (!newest.isEmpty()) {
                        // 格式化并打印明天的日期时间
                        endTime = LocalDateTime.parse(newest.get("startTime").toString(), isoFormatter).format(customFormatter);
                    }
                    //2 代表 环比逻辑处理 - 上期能耗
                    if (compareType.equals("1")) {
                        YoYStartTime = LocalDateTime.parse(startDateTime.minusYears(1).toString(), isoFormatter).format(customFormatter);
                        YoYendTime = startTime;
                    }
                } else {
                    //区间查询，根据结束时间，获取明年的00:00:00点
                    Year year = Year.parse(endDate, DateTimeFormatter.ofPattern("yyyy")).plusYears(1);
                    //获取开始时间与结束时间 用来做判断用 明天有没有数据, 没有数据则不进入
                    Map newest = getNewestTime(year.toString(), year.toString());
                    if (!newest.isEmpty()) {
                        // 格式化并打印明天的日期时间
                        endTime = LocalDateTime.parse(newest.get("startTime").toString(), isoFormatter).format(customFormatter);
                    }
                }
            } else {
                //2 代表 环比逻辑处理 - 上期能耗
                if (compareType.equals("1")) {
                    YoYStartTime = LocalDateTime.parse(startDateTime.minusYears(1).toString(), isoFormatter).format(customFormatter);
                    YoYendTime = LocalDateTime.parse(endDateTime.minusYears(1).toString(), isoFormatter).format(customFormatter);
                }
            }
        }
        Map map = new HashMap();
        /*用电量*/
        double eStartSum = this.powerHourFlowMapper.sumPowerAllNumber("1", startTime);
        double eEndSum = this.powerHourFlowMapper.sumPowerAllNumber("1", endTime);
        double eSumPower = 0;
        if (eStartSum != 0 && eEndSum != 0) {
            eSumPower = eEndSum - eStartSum;
        }
        //电的标准煤计算方式
        double eSumPowerCoal = 0d;
        eSumPowerCoal += PowerConvert.electricToCoal(eSumPower);
        map = new HashMap();
        map.put("sumPower", new BigDecimal(eSumPower).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        double eYoYStartSum = this.powerHourFlowMapper.sumPowerAllNumber("1", YoYStartTime);
        double eYoYEndSum = this.powerHourFlowMapper.sumPowerAllNumber("1", YoYendTime);
        double eYoYSumPower = 0;
        if (eYoYStartSum != 0 && eYoYEndSum != 0) {
            eYoYSumPower = eYoYEndSum - eYoYStartSum;
        }
        //环比 电的标准煤计算方式
        double eYoYSumPowerCoal = 0d;
        eYoYSumPowerCoal += PowerConvert.electricToCoal(eYoYSumPower);
        // 环比增长率
        if (eYoYSumPower > 0) {
            Double growthRate = (eSumPower - eYoYSumPower) / eYoYSumPower * 100; // 增长率
            BigDecimal b = new BigDecimal(growthRate);
            double growthRatef = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            map.put("growthRate", growthRatef);
        } else {
            map.put("growthRate", "-");
        }
        map.put("name", "用电量 (kwh)");
        //用电量
        result.put("eSumPower", map);
        /*用水量*/
        double wStartSum = this.powerHourFlowMapper.sumPowerAllNumber("2", startTime);
        double wEndSum = this.powerHourFlowMapper.sumPowerAllNumber("2", endTime);
        double wSumPower = 0;
        if (wStartSum != 0 && wEndSum != 0) {
            wSumPower = wEndSum - wStartSum;
        }
        //水的标准煤计算方式
        double wSumPowerCoal = 0d;
        wSumPowerCoal += PowerConvert.waterToCoal(wSumPower);

        map = new HashMap();
        map.put("sumPower", new BigDecimal(wSumPower).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        double wYoYStartSum = this.powerHourFlowMapper.sumPowerAllNumber("2", YoYStartTime);
        double wYoYEndSum = this.powerHourFlowMapper.sumPowerAllNumber("2", YoYendTime);
        double wYoYSumPower = 0;
        if (wYoYStartSum != 0 && wYoYEndSum != 0) {
            wYoYSumPower = wYoYEndSum - wYoYStartSum;
        }
        //环比 水的标准煤计算方式
        double wYoYSumPowerCoal = 0d;
        wYoYSumPowerCoal += PowerConvert.waterToCoal(wYoYSumPower);

        // 环比增长率
        if (wYoYSumPower > 0) {
            Double growthRate = (wSumPower - wYoYSumPower) / wYoYSumPower * 100; // 增长率
            BigDecimal b = new BigDecimal(growthRate);
            double growthRatef = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            map.put("growthRate", growthRatef);
        } else {
            map.put("growthRate", "-");
        }
        map.put("name", "用水量 (t)");
        //用水量
        result.put("wSumPower", map);
        /*用气量*/
        double gStartSum = this.powerHourFlowMapper.sumPowerAllNumber("3", startTime);
        double gEndSum = this.powerHourFlowMapper.sumPowerAllNumber("3", endTime);
        double gSumPower = 0;
        if (gStartSum != 0 && gEndSum != 0) {
            gSumPower = gEndSum - gStartSum;
        }
        //气的标准煤计算方式
        double gSumPowerCoal = 0d;
        gSumPowerCoal += PowerConvert.gasToCoal(gSumPower);

        map = new HashMap();
        map.put("sumPower", new BigDecimal(gSumPower).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        double gYoYStartSum = this.powerHourFlowMapper.sumPowerAllNumber("3", YoYStartTime);
        double gYoYEndSum = this.powerHourFlowMapper.sumPowerAllNumber("3", YoYendTime);
        double gYoYSumPower = 0;
        if (gYoYStartSum != 0 && gYoYEndSum != 0) {
            gYoYSumPower = gYoYEndSum - gYoYStartSum;
        }
        //环比 气的标准煤计算方式
        double gYoYSumPowerCoal = 0d;
        gYoYSumPowerCoal += PowerConvert.waterToCoal(gYoYSumPower);

        // 环比增长率
        if (gYoYSumPower > 0) {
            Double growthRate = (gSumPower - gYoYSumPower) / gYoYSumPower * 100; // 增长率
            BigDecimal b = new BigDecimal(growthRate);
            double growthRatef = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            map.put("growthRate", growthRatef);
        } else {
            map.put("growthRate", "-");
        }
        map.put("name", "用气量 (m3)");
        //用气量
        result.put("gSumPower", map);

        /* 综合能耗 - tec 标准煤 计算方式 */
        // 水电气的标准煤累加
        double allSumCoal = 0d;
        allSumCoal += eSumPowerCoal + wSumPowerCoal + gSumPowerCoal;
        // 环比 水电气的标准煤累加
        double allYoYSumCoal = 0d;
        allYoYSumCoal += eYoYSumPowerCoal + wYoYSumPowerCoal + gYoYSumPowerCoal;
        map = new HashMap();
        map.put("sumPower", new BigDecimal(allSumCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        // 环比增长率
        if (allYoYSumCoal > 0) {
            Double growthRate = (allSumCoal - allYoYSumCoal) / allYoYSumCoal * 100; // 增长率
            BigDecimal b = new BigDecimal(growthRate);
            double growthRatef = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            map.put("growthRate", growthRatef);
        } else {
            map.put("growthRate", "-");
        }
        //水的标准煤计算方式
        map.put("name", "综合能耗 (tec)");
        //综合能耗
        result.put("allSumPower", map);
        return result;
    }

    //获取数据库最新的时间格式 开始时间 与 结束时间
    public Map getNewestTime(String startDate, String endDate) {
        Map map = new HashMap();
        //获取当前时间
        PowerHourFlow startHourFlow = this.powerHourFlowMapper.selectOne(Wrappers.<PowerHourFlow>lambdaQuery()
                .like(PowerHourFlow::getTimeValue, startDate)
                .orderByAsc(PowerHourFlow::getTimeValue).last("LIMIT 1"));
        //获取上一条数据
        PowerHourFlow endHourFlow = this.powerHourFlowMapper.selectOne(Wrappers.<PowerHourFlow>lambdaQuery()
                .like(PowerHourFlow::getTimeValue, endDate)
                .orderByDesc(PowerHourFlow::getTimeValue).last("LIMIT 1"));
        if (com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(startHourFlow) && com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(endHourFlow)) {
            map.put("startTime", startHourFlow.getTimeValue().toString());
            map.put("endTime", endHourFlow.getTimeValue().toString());
        }
        return map;
    }

    //能耗趋势-综合能耗
    @Override
    public JSONObject powerIntegral(String startDate, String endDate, String compareType) throws ParseException {
        JSONObject jsonPower = new JSONObject();
        //日
        if (startDate.matches("\\d{4}-\\d{2}-\\d{2}") && endDate.matches("\\d{4}-\\d{2}-\\d{2}")) {
            LocalDate today = LocalDate.now();
            //当天数据
            if (startDate.equals(today.toString()) && endDate.equals(today.toString())) {
                //日能耗柱状图
                jsonPower = powerDayIntegral(startDate, endDate, compareType);
            } else {
                if (startDate.equals(endDate)) {
                    //其他天的数据
                    // jsonPower = powerDayLayer(startDate, endDate, energyType, compareType);
                } else {
                    // jsonPower = powerDaySectionLayer(startDate, endDate, energyType, compareType);
                }
            }
        }
        //月
        if (startDate.matches("^\\d{4}-(0[1-9]|1[0-2])$") && endDate.matches("^\\d{4}-(0[1-9]|1[0-2])$")) {
            //1.获取当前月
            YearMonth currentMonth = YearMonth.from(LocalDate.now());
            //前月数据
            if (startDate.equals(currentMonth.toString()) && endDate.equals(currentMonth.toString())) {
                // jsonPower = powerMonthLayer(startDate, endDate, energyType, compareType);
            } else {
                if (startDate.equals(endDate)) {
                    //  jsonPower = powerMonthLayer(startDate, endDate, energyType, compareType);
                } else {
                    // jsonPower = powerMonthSectionLayer(startDate, endDate, energyType, compareType);
                }
            }
        }
        // 年
        if (startDate.matches("^\\d{4}$") && endDate.matches("^\\d{4}$")) {
            //1.获取当前年
            Year month = Year.from(LocalDate.now());
            System.out.println();
            if (startDate.equals(month.toString()) && endDate.equals(month.toString())) {
                //  jsonPower = powerYearsLayer(startDate, endDate, energyType, compareType);
            } else {
                if (startDate.equals(endDate)) {
                    //   jsonPower = powerYearsLayer(startDate, endDate, energyType, compareType);
                } else {
                    //  jsonPower = powerYearsSectionLayer(startDate, endDate, energyType, compareType);
                }
            }
        }
        return jsonPower;
    }

    //能耗趋势 - 综合能耗 - 日能耗柱状图
    public JSONObject powerDayIntegral(String startDate, String endDate, String compareType) throws ParseException {
        JSONObject jsonPower = new JSONObject();
        /*图表通用数组*/
        JSONObject chartData = new JSONObject();

        List<String> xData = new ArrayList<>();
        List<Double> yElecData = new ArrayList<>();//电
        List<Double> yWaterData = new ArrayList<>();//水
        List<Double> yGasData = new ArrayList<>();//水
        List<Double> yData2 = new ArrayList<>();//其他
        //图层时间
        String layerStartTime = null;
        String layerEndTime = null;
        String otherStartTime = null;
        String otherEndTime = null;
        List<Map<String, Object>> otherChartPowerList = new ArrayList<>();

        // Create图层时间
        layerStartTime = startDate + " 01";//开始时间
        // 解析给定的日期字符串
        LocalDate givenDate = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        // 获取明天的日期
        LocalDate nextDay = givenDate.plusDays(1);
        layerEndTime = nextDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00";
        if (compareType.equals("2")) {
            // Create图层其他时间
            // 获取昨天的日期
            LocalDate previousDay = givenDate.minusDays(1);
            otherStartTime = previousDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 01";
            otherEndTime = endDate + " 00";
            //其他时间段
            otherChartPowerList = this.powerHourFlowMapper.powerAnalyse(otherStartTime, otherEndTime, "1");
        }
        /* 图表 */
        //最新数据
        //电
        List<Map<String, Object>> elecList = this.powerHourFlowMapper.powerAnalyse(layerStartTime, layerEndTime, "1");
        //水
        List<Map<String, Object>> waterList = this.powerHourFlowMapper.powerAnalyse(layerStartTime, layerEndTime, "1");
        //气
        List<Map<String, Object>> gasList = this.powerHourFlowMapper.powerAnalyse(layerStartTime, layerEndTime, "1");
        System.out.println("电：" + elecList);
        System.out.println("水：" + waterList);
        System.out.println("气：" + gasList);

        for (int h = 0; h < 24; h++) {
            String strHour = String.format("%02d", h);
            xData.add(strHour);
            //电
            List<Map<String, Object>> elecData = elecList.stream().filter(bo -> bo.get("createTime").equals(strHour)).collect(Collectors.toList());
            Double powerElecData = null;
            Double otherData = null;
            if (!elecData.isEmpty()) {
                powerElecData = Double.parseDouble(elecData.get(0).get("incrValue").toString());
                double eSumPowerCoal = 0d;
                eSumPowerCoal += PowerConvert.electricToCoal(powerElecData);
                yElecData.add(new BigDecimal(eSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            } else {
                yElecData.add(0.0);
            }

            //水
            List<Map<String, Object>> waterData = waterList.stream().filter(bo -> bo.get("createTime").equals(strHour)).collect(Collectors.toList());
            if (!waterData.isEmpty()) {
                powerElecData = Double.parseDouble(waterData.get(0).get("incrValue").toString());
                double wSumPowerCoal = 0d;
                wSumPowerCoal += PowerConvert.waterToCoal(powerElecData);
                yWaterData.add(new BigDecimal(wSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            } else {
                yWaterData.add(0.0);
            }
            //气
            List<Map<String, Object>> gasData = gasList.stream().filter(bo -> bo.get("createTime").equals(strHour)).collect(Collectors.toList());
            if (!gasData.isEmpty()) {
                powerElecData = Double.parseDouble(gasData.get(0).get("incrValue").toString());
                double gSumPowerCoal = 0d;
                gSumPowerCoal += PowerConvert.gasToCoal(powerElecData);
                yGasData.add(new BigDecimal(gSumPowerCoal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            } else {
                yGasData.add(0.0);
            }
        }
        List<String> legend = new ArrayList<>();

        //电
        JSONObject elec = new JSONObject();
        elec.put("name", "电");
        elec.put("data", yElecData);
        chartData.put("elec", elec);
        legend.add("电");
        //水
        JSONObject water = new JSONObject();
        water.put("name", "水");
        water.put("data", yWaterData);
        chartData.put("water", water);
        legend.add("水");
        //气
        JSONObject gas = new JSONObject();
        gas.put("name", "气");
        gas.put("data", yGasData);
        legend.add("气");
        chartData.put("data", legend);
        chartData.put("gas", gas);
        chartData.put("xData", xData);
        jsonPower.put("chartData", chartData);//图标
        //  jsonPower.put("tableData", chartPowerList);//表格
        return jsonPower;
    }

}